﻿using Help;
using Model;
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;

namespace BLLA
{
    public partial class User_District_T : BaseBLL<Model.User_District_T>, IBLL.IUser_District_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();

        #region 获取用户区域地址全部信息                
        /// <summary>
        /// 获取用户区域地址全部信息
        /// </summary>
        /// <returns></returns>
        public string Get_User_Districts()
        {
            try
            {
                List<Model.User_District_T> udtList = base.GetListBy(u => true);
                List<Model.User_District_T> rootDistrict = udtList.Where(u => u.DistrictID.Length == 3).OrderBy(u => u.DelFormMon).ToList();//找根节点 
                List<UserDistrictInfo> user_district = new List<UserDistrictInfo>();
                if (rootDistrict == null || rootDistrict.Count() == 0)
                {
                    result.BS = "0";
                    result.Msg = "没有找到根节点";
                    return os.StringOfObject(result, 1);
                }
                //构建树形结构
                foreach (Model.User_District_T item in rootDistrict)
                {
                    UserDistrictInfo odt = new UserDistrictInfo
                    {
                        ID = item.ID,
                        DistrictID = item.DistrictID,
                        DistrictName = item.DistrictName,
                        DelFormMon = item.DelFormMon,
                        DistrictState = item.DistrictState,
                        Children = new List<UserDistrictInfo>()
                    };
                    AddSonNode(odt.DistrictID, odt, udtList);
                    result.total = odt.Children.Count + 1;
                    user_district.Add(odt);
                }

                if (user_district != null & user_district.Count > 0)
                {
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = user_district;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW(" 获取用户区域地址全部信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
            }
            return os.StringOfObject(result, 1);
        }

        /// <summary>
        /// 添加子集
        /// </summary>
        /// <param name="p">父ID</param>
        /// <param name="odt">父节点</param>
        /// <param name="roomDepList">数据集合</param>
        private void AddSonNode(string p, UserDistrictInfo odt, List<Model.User_District_T> roomDisList)
        {
            int i = 0;
            if (p.Length == 3)
            {
                i = p.Length + 3;
            }
            else
            {
                i += p.Length + 3;
            }
            List<Model.User_District_T> dis = roomDisList.Where(u => u.DistrictID.StartsWith(p) & u.DistrictID.Length == i).OrderBy(u => u.DelFormMon).ToList(); //找到下一级
            if (dis.Count <= 0)
            {
                //Log.Debug("AddSonNode", "父节点" + p + "没下一级");
            }
            foreach (Model.User_District_T item in dis)
            {
                //Log.Debug("父节点" + p + ",下节点：" + item.ClassID);
                UserDistrictInfo dt = new UserDistrictInfo
                {
                    ID = item.ID,
                    DistrictID = item.DistrictID,
                    DistrictName = item.DistrictName,
                    DelFormMon = item.DelFormMon,
                    DistrictState = item.DistrictState,
                    Children = new List<UserDistrictInfo>()
                };
                odt.Children.Add(dt);
                AddSonNode(item.DistrictID, dt, roomDisList);
            }
        }
        #endregion

        /// <summary>
        /// 根据区域ID获取区域地址信息
        /// </summary>
        /// <param name="DistrictID">区域ID</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string Get_User_DistrictsByDistrictID(string DistrictID, string YZM, int RETID)
        {
            try
            {
                #region 匹配验证码
                if (YZM != Help.ALL_DataV.YZM)
                {
                    result.BS = "-88";
                    result.Msg = "验证码错误！";
                    return os.StringOfObject(result, RETID);
                }
                #endregion 
                List<Model.User_District_T> ls = base.GetListBy(u => true).Where(u => u.DistrictID == DistrictID).ToList();

                if (ls != null & ls.Count > 0)
                {
                    object tem = from m in ls select new { m.DistrictID, m.DistrictName, m.DelFormMon, m.DistrictState };
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = tem;
                    result.total = ls.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }

                return os.StringOfObject(result, RETID);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取区域地址信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, RETID);
            }
        }

        /// <summary>
        /// 更新用户区域地址
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="json">更新信息</param>
        /// <param name="tag">操作标签（1：新增；2：修改；3：删除）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式（1：JSON；2：XML）</param>
        /// <returns></returns>
        public string SetUser_District(int OperID, string json, int tag, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.User_District_T info = ParseClass<Model.User_District_T>.StrDeserialize(json, RETID);
                string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (tag)
                {
                    case 1:
                        T = "新增";
                        List<Model.User_District_T> ls = base.GetListBy(u => true).Where(u => u.DistrictID == info.DistrictID).ToList();
                        if (ls.Count() > 0)
                        {
                            int i = 0;
                            if (info.DistrictID.Length == 3)
                            {
                                i = info.DistrictID.Length + 3;
                            }
                            else
                            {
                                i += info.DistrictID.Length + 3;
                            }
                            List<Model.User_District_T> dis = base.GetListBy(u => true).Where(u => u.DistrictID.StartsWith(info.DistrictID) & u.DistrictID.Length == i).OrderBy(u => u.DistrictID).ToList();
                            if (dis.Count() == 0)
                            {
                                info.DistrictID = info.DistrictID + "001";
                            }
                            else
                            {
                                Model.User_District_T reg = base.GetListBy("select * from  User_District_T where DistrictID like (select max(cast(DistrictID as varchar)) as DistrictID from User_District_T  where len(cast(DistrictID as varchar))=" + i + " and (DistrictID LIKE '%" + info.DistrictID + "%'))").First();
                                if (reg != null)
                                {
                                    var xx = reg.DistrictID;  //取得同类型的DistrictID最大值
                                    int j = int.Parse(xx);
                                    string k = ((j + 1).ToString()).ToString().PadLeft(i, '0');    //前面补0
                                    info.DistrictID = k;
                                }
                            }
                            ret = base.Add(info);
                        }
                        break;
                    case 2:
                        T = "修改";
                        Model.User_District_T tmp = base.GetListBy(u => true).Where(u => u.DistrictID == info.DistrictID).First();
                        info.ID = tmp.ID;
                        Help.FuZhi<Model.User_District_T>.FZ(ref tmp, info);
                        ret = base.Modify(tmp);
                        break;
                    case 3:
                        T = "删除";
                        List<Model.User_District_T> list_tmp = base.GetListBy(u => true).Where(u => u.DistrictID == info.DistrictID).ToList();
                        if (list_tmp != null && list_tmp.Count > 0)
                        {
                            Model.User_District_T tmp2 = list_tmp.First();
                            ret = base.Del(tmp2);       //删除选中行的数据
                            if (ret > 0)
                            {
                                List<Model.User_District_T> list_tmp2 = base.GetListBy(u => true).Where(u => u.DistrictID.Contains(info.DistrictID) && u.DistrictID.Length == 9).ToList();
                                if (list_tmp2 != null && list_tmp2.Count > 0)
                                {
                                    foreach (var item in list_tmp2)
                                    {
                                        ret = base.Del(item);   //删除选中行的子数据
                                    }
                                }
                            }
                        }
                        break;
                }

                if (ret > 0)
                {
                    // 将操作记录到日志表中
                    Model.Order_OperationFlow_T Log = new Model.Order_OperationFlow_T();
                    Log.OperationTitle = "更新用户区域地址";
                    Log.OperationText = T + "用户区域地址成功";
                    Log.OperationType = "1F0006";
                    Log.OperationRes = "成功";
                    Log.OperationUser = OperID;
                    string str_log = os.StringOfObject(Log, RETID);
                    bool isSuccess = new Order_OperationFlow_T().AddOrder_OperationFlow(str_log, RETID);
                    if (!isSuccess)
                    {
                        WriteLog.WriteW("新增系统操作流水失败");
                    }
                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("更新用户区域地址失败：" + ex.Message);
                result.BS = "-1";
                result.Msg = "更新失败";
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        #region 微信端添加地址页面获取地址区域
        /// <summary>
        /// 二级地址区域
        /// </summary>
        /// <param name="DistrictID">一级区域ID</param>
        /// <returns></returns>
        public string Get_User_DistrictsTwoByDistrictID(string DistrictID)
        {
            try
            {
                List<Model.User_District_T> ls = base.GetListBy(u => true).Where(u => u.DistrictID.StartsWith(DistrictID) && u.DistrictID.Length == 6 && u.DistrictState == 1).ToList();

                if (ls != null & ls.Count > 0)
                {
                    object tem = from m in ls select new { m.DistrictID, m.DistrictName };
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = tem;
                    result.total = ls.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }

                return os.StringOfObject(result, 1);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取区域地址信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, 1);
            }
        }

        /// <summary>
        /// 三级地址区域
        /// </summary>
        /// <param name="DistrictID">二级区域ID</param>
        /// <returns></returns>
        public string Get_User_DistrictsThreeByDistrictID(string DistrictID)
        {
            try
            {
                List<Model.User_District_T> ls = base.GetListBy(u => true).Where(u => u.DistrictID.StartsWith(DistrictID) && u.DistrictID.Substring(0, 6) == DistrictID && u.DistrictID.Length == 9 && u.DistrictState == 1).ToList();

                if (ls != null & ls.Count > 0)
                {
                    object tem = from m in ls select new { m.DistrictID, m.DistrictName };
                    result.BS = "1";
                    result.Msg = "查询成功";
                    result.rows = tem;
                    result.total = ls.Count;
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "查询不到数据";
                }

                return os.StringOfObject(result, 1);
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("获取区域地址信息失败：" + ex.Message);
                result.BS = "-99";
                result.Msg = "系统错误！";
                return os.StringOfObject(result, 1);
            }
        }
        
        #endregion
    }
}
